package com.zy.community.common.component.minio;

import com.zy.community.common.core.domain.r.ZyResult;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.UUID;

/**
 * minio的组件
 */
@Component
public class MinioComponent {

    private final static Logger log = LoggerFactory.getLogger(MinioComponent.class);

    private final MinioProperty minioProperty;


    public MinioComponent(MinioProperty minioProperty) {
        this.minioProperty = minioProperty;
    }

    private MinioClient minioClient;

    @PostConstruct
    private void initMinioClient() {
        try {
            minioClient = MinioClient.builder().endpoint(minioProperty.getUrl())
                    .credentials(minioProperty.getAccount(), minioProperty.getSecret()).build();

            log.info("Minio客户端初始化成功");

            if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperty.getBucketName()).build())) {
                //初始化bucket
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperty.getBucketName()).build());
                log.info("存储桶[{}]初始化", minioProperty.getBucketName());
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.error("Minio客户端初始化失败:[{}]", e.getMessage());
        }
    }


    /**
     * 上传文件
     *
     * @param file 文件
     * @return 下载地址
     */
    public ZyResult<String> uploadByFile(File file) {
        try {
            InputStream fileInputStream = new FileInputStream(file);
            return baseUpload(fileInputStream, file.getName());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("文件转换数据流失败:[{}]", e.getMessage());
            return ZyResult.fail(500, e.getMessage());
        }


    }


    /**
     * 上传文件
     *
     * @param file 文件
     * @return 下载地址
     */
    public ZyResult<String> uploadByFile(MultipartFile file) {
        try {
            InputStream fileInputStream = file.getInputStream();
        return baseUpload(fileInputStream,file.getOriginalFilename());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("文件转换数据流失败:[{}]", e.getMessage());
            return ZyResult.fail(500, e.getMessage());
        }
    }

    /**
     * 基础上传
     *
     * @param is         流
     * @param fileName 文件名称
     * @return 结果
     */
    private ZyResult<String> baseUpload(InputStream is, String fileName) {
        try {
            String objectId = UUID.randomUUID().toString().replaceAll("-", "")+"/"+fileName;
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(minioProperty.getBucketName())
                    .object(objectId)
                    .stream(is, is.available(), -1)
                    .build());
            String viewUrl = minioProperty.getUrl() + "/"+minioProperty.getBucketName() + "/" + objectId;
            return ZyResult.data(viewUrl);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("上传文件异常:[{}]", e.getMessage());
            return ZyResult.fail(500, e.getMessage());
        }
    }

    /**
     * 获取后缀名称
     *
     * @param name 文件名称
     * @return 返回
     */
    private String getExtendName(String name) {
        String extentName = "";
        if (name.contains(".")) {
            extentName = name.substring(name.lastIndexOf("."));
        }
        return extentName;
    }

}
